#!/usr/bin/env python
# coding=utf-8
# Created on 2014-1-17
#
from model.model import *
from model.mail import send_mail
from tornado import ioloop, web, httpserver
from apscheduler.scheduler import Scheduler
from config.config import __VERSION__, PORT, initLog, CBGW_ADDR, BRAND, SMSNAME, SMSPWD, CALL_RATE, SMS_RATE, UNIT, CRENT
import simplejson as json, urllib2, urllib, math
import threading
import thread
# 当前日期
def get_dt():
    return time.strftime('%Y-%m-%d', time.localtime(time.time()))

# 当前时间段
def get_tt():
    return time.strftime('%H', time.localtime(time.time()))

# 版本信息
class versionHandler(web.RequestHandler):
    def get(self):
        self.finish(__VERSION__)


def scan_task():
    print "test"


# 接口服务(http)
def http_server():
    server = httpserver.HTTPServer(Application())
    server.listen(PORT)
    ioloop.IOLoop.instance().start()

# 版本信息
class versionHandler(web.RequestHandler):
    def get(self):
        self.finish(__VERSION__)
        print "2222222"


# 应答接口,
class comebackHandler(web.RequestHandler):
    '''计费模式 6==math.ceil(通话时长/6.0)*(费率/10); 60==math.ceil(通话时长/6.0)*费率    '''

    def get(self):
        try:
            logger.info("收到回调url任务:%s" % self)
            number = self.get_argument('caller', '')  # 主叫号码
            if not number:
                logger.info(u"杀杀杀")
                return
            else:
                caller = number[-11:]
            redirectret = int(self.get_argument('redirectret', ''))  # 是否转客服
            extend = self.get_argument('extend', '')  # 扩展信息,用户id,计费模式,费率
            acalltime = int(self.get_argument('Acalltime', 0))  # A路通话时长
            bcalltime = int(self.get_argument('Bcalltime', 0))  # B路通话时长
            ex = json.loads(extend)
            user_id = int(ex.get('user_id', ''))  # 用户ID
            model = int(ex.get('model', UNIT))  # 计费模式,默认6秒计费单元
            rate = float(ex.get('rate', CALL_RATE))  # 默认费率,5分
            task_id = int(ex.get('task_id', ''))  # 群呼任务ID
            numid = int(ex.get('numid', ''))  # 群呼号码ID
            if model == 6:
                fee = math.ceil((acalltime + bcalltime) / 6.0) * (rate / 10)  # 6秒计费
            elif model == 60:
                fee = math.ceil((acalltime + bcalltime) / 6.0) * rate  # 60秒计费
            else:
                logger.info(u"计费模式错误:%s" % model)
            comebacknotify_param = {'numid': numid, "Acalltime": acalltime, 'Bcalltime': bcalltime,
                                    "redirectret": redirectret, "caller": caller, 'task_id': task_id, "fee": fee,
                                    "user_id": user_id}
            logger.info("收到回调任务id:%s,回调任务下面参数:%s" % (task_id, comebacknotify_param))
            #             redis_model.in_comebakcallnotify(comebacknotify_param)

            task_call_radis_name = PRE_CALL_HASH_NAME + str(task_id)  # 已经发送到cbgw的号码
            task_finish_radis_name = FINISH_HASH_NAME + str(task_id)  # 执行完成号码hash
            # 从呼叫call数据中获取已经呼叫的次数
            current_call_tasknum_data = redis_model.hget_value(task_call_radis_name, numid)
            if not current_call_tasknum_data:
                res = ({"result": 5})  # 未知错误
                self.finish(res)
                return
            current_call_tasknum_data = eval(current_call_tasknum_data)
            call_qty = int(current_call_tasknum_data['call_qty'])  # 已经呼叫的次数
            comebacknotify_param['call_qty'] = call_qty
            if acalltime <= 0:  # 说明没有接通
                # 从参数中获取当前任务的重发次数
                task_cfg = redis_model.hget_value(CFG_HASH_NAME, str(task_id))
                task_cfg = eval(task_cfg)
                repeats_qty = int(task_cfg['repeats_qty'])
                if repeats_qty > 0:  # 需要重复呼叫(的次数)
                    if call_qty < (repeats_qty + 1):  # 已经呼叫的次数小于可以重呼次数(说明：重呼2次，说明可以呼叫3次）
                        redis_model.hdelete(task_call_radis_name, numid)  # 删除call的 hash 号码
                        current_call_tasknum_data['call_qty'] = call_qty + 1
                        redis_model.hset(task_call_radis_name, numid, current_call_tasknum_data)  # 重新加入到call hash表中
                    else:
                        redis_model.hset(task_finish_radis_name, numid, comebacknotify_param)  # 加入执行完成号码hash
                        redis_model.hdelete(task_call_radis_name, numid)  # 删除call的 hash 号码
                        call_num_cnt = redis_model.hlen(task_call_radis_name)  # 当前任务呼叫中的号码数目
                        task_cfg['call_num_cnt'] = call_num_cnt  # 设置当前并发数目
                        redis_model.hset(CFG_HASH_NAME, task_id, task_cfg)
                    res = ({"result": 0})
                else:  # 不需要重复呼叫
                    redis_model.hset(task_finish_radis_name, numid, comebacknotify_param)  # 加入执行完成号码hash
                    redis_model.hdelete(task_call_radis_name, numid)  # 删除call的 hash 号码
                    call_num_cnt = redis_model.hlen(task_call_radis_name)  # 当前任务呼叫中的号码数目
                    task_cfg['call_num_cnt'] = call_num_cnt  # 设置当前并发数目
                    redis_model.hset(CFG_HASH_NAME, task_id, task_cfg)
                    res = ({"result": 0})
            else:  # 接通
                redis_model.hset(task_finish_radis_name, numid, comebacknotify_param)  # 加入执行完成号码hash
                redis_model.hdelete(task_call_radis_name, numid)  # 删除call的 hash 号码
                call_num_cnt = redis_model.hlen(task_call_radis_name)  # 当前任务呼叫中的号码数目
                task_cfg['call_num_cnt'] = call_num_cnt  # 设置当前并发数目
                redis_model.hset(CFG_HASH_NAME, task_id, task_cfg)
                res = ({"result": 0})
        except:
            logger.error('have a error', exc_info=True)
            res = ({"result": 5})  # 未知错误
        self.finish(res)


class Application(web.Application):
    def __init__(self):
        handlers = [
            (r"/comeback", comebackHandler),
            (r"/version", versionHandler)
        ]
        settings = {
            "debug": True,
        }
        web.Application.__init__(self, handlers, **settings)


# (计费,更新号码状态,任务状态)
def comebakcallnotify():
    while True:
        time.sleep(10)
        print 1111
        continue
        comebakcall = None
        try:
            task_cfg_keys = redis_model.hgetkeys(CFG_HASH_NAME)  # 得到缓存里面的参数key
            if task_cfg_keys:
                for task_id in task_cfg_keys:
                    task_cfg = redis_model.hget_value(CFG_HASH_NAME, task_id)
                    task_cfg = eval(task_cfg)
                    status = task_cfg['status']  # 任务当前执行状态  exec执行中，finished发送完成
                    if status != 'exec':  # 只要有发送去cbgw数据，就要准备计费了
                        #                         task_call_radis_name = PRE_CALL_HASH_NAME + str(task_id)  # 发送到cbgw的号码redis
                        #                         task_call_radis_name_len = redis_model.hlen(task_call_radis_name)
                        #                         if task_call_radis_name_len <= 0:  # 发送的号码都删除了
                        #                             redis_model.hdelete(CFG_HASH_NAME, task_id)  # 任务参数删除
                        #                             logger.info(u"删除任务:%s 的参数" % task_id)
                        #                             continue
                        task_finish_radis_name = FINISH_HASH_NAME + str(task_id)  # 执行完成号码hash
                        comebakcalls_keys = redis_model.hgetkeys(task_finish_radis_name)  # 获取执行完成的号码keys
                        if comebakcalls_keys:  # 有号码返回就计费
                            for numid in comebakcalls_keys:
                                try:
                                    comebakcalls = redis_model.hget_value(task_finish_radis_name, numid)
                                    # comebakcalls = redis_model.out_list(FINISH_HASH_NAME, SEND_CBGW_PER)
                                    logger.info(u"扫描任务id：%s,扫描计费改状态:%s" % (task_id, comebakcalls))
                                    comebakcall = comebakcalls
                                    comebakcall_dict = eval(comebakcall)
                                    acalltime = comebakcall_dict['Acalltime']
                                    call_qty = comebakcall_dict['call_qty']  # 呼叫的次数
                                    bcalltime = comebakcall_dict['Bcalltime']
                                    redirectret = comebakcall_dict['redirectret']
                                    caller = comebakcall_dict['caller']
                                    task_id = comebakcall_dict['task_id']
                                    fee = comebakcall_dict['fee']
                                    user_id = comebakcall_dict['user_id']
                                    numid = comebakcall_dict['numid']
                                    write_num_data(fee, acalltime, bcalltime, redirectret, caller, task_id, user_id,
                                                   numid, call_qty)  # 写入呼叫数据
                                except:
                                    logger.error('have a error at write_num_data', exc_info=True)
                                else:  # 无异常执行
                                    redis_model.hdelete(task_finish_radis_name, numid)  # 删除完成的号码记录
        #                             redis_model.hset(task_finish_radis_name, numid, comebakcall)
        #                             redis_model.hdelete(CFG_HASH_NAME, task_id)  # 任务参数删除
        #                             logger.info(u"删除任务:%s 的参数" % task_id)
        except:
            logger.error('have a error', exc_info=True)


#         time.sleep(3)
#     try:
#         comebakcalls = redis_model.out_comebakcallnotify(50)
#         if not comebakcalls:
#             return
#         for comebakcall in comebakcalls:
#             comebakcall_dict = eval(comebakcall)
# #             comebacknotify_param = {"Acalltime":acalltime , 'Bcalltime' : bcalltime , "redirectret" : redirectret , "caller" : caller , 'task_id' : task_id , "fee" : fee , "user_id" :user_id}
#             acalltime = comebakcall_dict['Acalltime']
#             bcalltime = comebakcall_dict['Bcalltime']
#             redirectret = comebakcall_dict['redirectret']
#             caller = comebakcall_dict['caller']
#             task_id = comebakcall_dict['task_id']
#             fee = comebakcall_dict['fee']
#             user_id = comebakcall_dict['user_id']
#             write_num_data(fee,acalltime, bcalltime, redirectret, caller, task_id,user_id)  # 写入呼叫数据
# #             call_deduct(fee, user_id)  # 群呼扣费
# #             write_call_fee(fee, caller, task_id)  # 记录费用
#             redis_model.rm_comebakcallnotify(comebakcall)
#     except:
#         redis_model.in_comebakcallnotify(comebakcall)
#         logger.error('have a error', exc_info=True)


def tongjibinfa():
    pass
def main():
    sched = Scheduler()
    sched.add_interval_job(scan_task, seconds=30)  # 呼叫
    # sched.add_interval_job(scan_sms, seconds=5)                     # 发送短信
    # sched.add_interval_job(sms_deduction, minutes=1)                # 短信扣费
#     sched.add_interval_job(comebakcallnotify, seconds=3)  # 计费,更新号码状态,任务状态
    thread.start_new_thread(comebakcallnotify, ())
    
    # sched.add_interval_job(tongjibinfa, seconds=1)  # 呼叫
#     thread.start_new_thread(send_num_to_cbgw, ())
#     send_num_to_cbgw(1)
    # thread.start_new_thread(comebakcallnotify, ())    
#     threads.append(threading.Thread(target=comebakcallnotify, args=()))
#     启动所有线程
#     for t in threads:
#        t.start()
        
        
    # sched.add_interval_job(update_task, seconds=10)  # 更新任务状态
    # sched.add_cron_job(task_redis_data_clean, hour=21, minute=0, second=0)  # 定期清理redis缓存垃圾信息
    # sched.add_cron_job(report_task, hour=22, minute=0, second=0)  # 群呼任务报表
    # sched.add_cron_job(report_expenses, hour=23, minute=0, second=0)  # 任务日消费报表
    sched.start()
    initLog()
    http_server()
        
if __name__ == "__main__":
    main()

